package net.angrynut.web.handler.handlerBean;

import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.HttpRequestHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Min;
import javax.validation.constraints.Size;
import java.io.IOException;
import java.util.Date;

/**
 * 这里演示如何使用注解 `@{@link ConfigurationProperties}`。
 *
 * 要使之生效，需要为每个 field 设置一个 public 的 setter。
 */
@Component("/demo/annotation/configuration-properties")
@ConfigurationProperties(prefix = "demo.config-props")
@Data
@Validated
public class DemoConfigurationPropertiesHandler implements HttpRequestHandler {

    @Size(min = 3)
    private String name;

    @Min(1)
    private int count;

    // 需要一个注册到 bean conversionService 中的类型转换器
    private Date date;

    @Override
    public void handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json; charset=utf-8");
        JSONObject json = new JSONObject();
        json.put("name", name);
        json.put("count", count);
        json.put("date", date);
        response.getWriter().append(json.toJSONString()).flush();
    }
}